//
//  ViewController.m
//  CoreData_demo
//
//  Created by macOS on 2016/12/21.
//  Copyright © 2016年 macOS. All rights reserved.
//

#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "Employee+CoreDataProperties.h"

#import "Departmenter+CoreDataClass.h"

#define ENTITYNAME @"Employee"

#define DEPARTMENTER @"Departmenter"
@interface ViewController ()



@property(nonatomic, strong) NSManagedObjectContext *context ;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    
 
    
    
    
}
- (IBAction)add:(id)sender {
    [self addEmployee];
}
- (IBAction)creat:(id)sender {
    
    //创建模型文件
    
    
    
    //上下文   //关联数据库
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
    
    self.context = context;
    
    //模型文件 从bundle中读取
    NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil] ;
    
    //持久化储存调度器 把数据库保存到一个文件 而不是内存
    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    
    
    
    //配置数据库储存路径
    NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *sqlitepath = [doc stringByAppendingPathComponent:@"company.sql"];
    
    NSLog(@"----%@",sqlitepath);
    [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitepath] options:nil error:nil];
    
    //告诉coredata 数据库的名字和路径
    
    context.persistentStoreCoordinator  = coordinator;
    
    
}
- (IBAction)dele:(id)sender {
    
    
    
}
- (IBAction)query:(id)sender {
    
    
    
    //[self queryWtihFenye];
    [self mohuQuery];

    
}


//查询所有
- (void)queryAll{
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:ENTITYNAME];
    
        //NSPredicate *predicate = [NSPredicate predicateWithFormat:@"depart.deparNo = %@", @"1002"];
    
        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
    
        //request.predicate = predicate;
    
        request.sortDescriptors =@[sort];
        NSError *err = nil;
    
        NSArray *result = [self.context executeFetchRequest:request error:&err];
    
        [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSLog(@"%@",obj);
        }];
    
        if (err) {
            NSLog(@"query err: %@",err);
        }

}

//分页查询

- (void)queryWtihFenye{
  
    static int  offset = 0;
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:ENTITYNAME];
    
    //NSPredicate *predicate = [NSPredicate predicateWithFormat:@"depart.deparNo = %@", @"1002"];
    
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
    
    //request.predicate = predicate;
    
    request.sortDescriptors =@[sort];
    
    //分页的起始索引
    request.fetchOffset = offset ;
    request.fetchLimit = 5;
    
    
    NSError *err = nil;
    
    NSArray *result = [self.context executeFetchRequest:request error:&err];
    
    [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%@",obj);
    }];
    
    if (err) {
        NSLog(@"query err: %@",err);
    }
   
    if (result.count == 0) {
        NSLog(@"没有更多数据了~~~~");
    }else{
      
        NSLog(@"当前第%@条",@(offset+(result.count)));
         offset +=5;
    
    }
    
    
}

//模糊查询
- (void)mohuQuery{
   
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:ENTITYNAME];
    
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"2"];
    
        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
    
        request.predicate = predicate;
    
        request.sortDescriptors =@[sort];
        NSError *err = nil;
    
        NSArray *result = [self.context executeFetchRequest:request error:&err];
    
        [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSLog(@"%@",obj);
        }];
    
        if (err) {
            NSLog(@"query err: %@",err);
        }

    
    
}


- (void)addEmployee{
    
    
    static int no = 1000;
    
    Departmenter *departer = [NSEntityDescription insertNewObjectForEntityForName:DEPARTMENTER inManagedObjectContext:self.context];
    departer.name = @"技术部门—ios";
    departer.createDate = [NSDate date];
    departer.deparNo = [@(no++) stringValue];
    
    
    
    
    
    
    
    Employee *employee = [NSEntityDescription insertNewObjectForEntityForName:ENTITYNAME inManagedObjectContext:self.context];
    
    static int i = 1;
    employee.name = [NSString stringWithFormat:@"wangsujin_%@",@(i)];
    employee.height = 170.0;
    employee.birthday = [NSDate date];
    employee.depart = departer;
    NSError *err = nil;
    [self.context save:&err];
    
    if (err) {
        NSLog(@"coredata add Err ：%@",err);
    }else{
        NSLog(@"插入成功");
    }
    i ++;
}

@end
